package persistent

import (
	"errors"
	"gitee.com/CrazyMage/lite-note/internal/entity"
	"gorm.io/gorm"
)

type NoteRepo struct {
	*gorm.DB
}

func NewNoteRepo(db *gorm.DB) *NoteRepo {

	return &NoteRepo{db}
}

func (nr *NoteRepo) CreateNote(note *entity.Note) error {

	return nr.DB.Create(note).Error

}

func (nr *NoteRepo) ListNodeByPages(uid uint, pageNumber, pageSize int) (*[]entity.Note, error) {

	offset := (pageNumber - 1) * pageSize

	var notes []entity.Note

	res := nr.DB.
		Where("uid =?", uid).
		Order("created_at DESC"). // 按创建时间倒序（重要：确保分页顺序稳定）
		Offset(offset).
		Limit(pageSize).
		Find(&notes)
	if res.Error != nil {
		if errors.Is(res.Error, gorm.ErrRecordNotFound) {
			// 无记录时返回空列表而非nil
			return &[]entity.Note{}, nil
		}
		return nil, res.Error
	}

	return &notes, nil

}

func (nr *NoteRepo) GetNoteById(id int) (*entity.Note, error) {
	var note entity.Note

	res := nr.DB.Where("Id = ?", id).First(&note)
	if errors.Is(res.Error, gorm.ErrRecordNotFound) {
		return nil, errors.New("笔记不存在")
	} else if res.Error != nil {
		return nil, res.Error

	}
	return &note, nil

}

func (nr *NoteRepo) DelNoteById(id int) error {
	result := nr.DB.Delete(&entity.Note{}, id)
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		return errors.New("笔记不存在或已被删除")
	}
	return nil
}

func (nr *NoteRepo) UpdateNoteById(note *entity.Note) error {
	result := nr.DB.Model(&entity.Note{}).Where("id = ?", note.ID).Updates(note)
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		return errors.New("笔记不存在")
	}

	return nil
}

func (nr *NoteRepo) QueryByTitle(uid int, title string) (*[]entity.Note, error) {

	var notes []entity.Note
	result := nr.DB.Where("uid =?", uid).Where("title LIKE ?", "%"+title+"%").Find(&notes)
	if errors.Is(result.Error, gorm.ErrRecordNotFound) {
		return &[]entity.Note{}, nil // 返回空切片而非nil
	} else if result.Error != nil {
		return nil, result.Error
	}
	return &notes, nil
}
